package com.mti.zhpt.base;

import java.util.HashSet;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.mti.zhpt.utils.SnowFlake;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * @classDesc: 功能描述:(service基础类)
 * @author 徐宝振
 * @createTime: 2018年8月3日 下午2:15:40
 * @version: v1.0
 * @copyright:上海道枢信息技术有限公司
 */
public abstract class BaseServiceImpl<T extends BaseEntity> implements BaseService<T> {

	@Autowired
	public SnowFlake snowFlake;
	
	@Autowired
	public BaseMapper<T> baseMapper;

	@Override
	public int save(T entity) {
		// 保存初始化
		if (StringUtils.isBlank(entity.getId())) {
			entity.setId(snowFlake.nextId());
		}
		return baseMapper.insertSelective(entity);
	}

	@Override
	public int batchSave(List<T> list) {
		if (list!=null&&list.size()>0){
			for (int i = 0; i < list.size(); i++) {
				T entity = list.get(i);
				if (StringUtils.isBlank(entity.getId())) {
					entity.setId(snowFlake.nextId());
				}
			}
		}
		return baseMapper.insertList(list);
	}

	@Override
	public int delete(String id) {
		return baseMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int delete(T entity) {
		return baseMapper.delete(entity);
	}

	/**
	 * 通过主键更新全部字段 根据主键更新实体全部字段，会将为空的字段在数据库中置为NULL
	 */
	@Override
	public int updateByPrimaryKey(T entity) {
		return baseMapper.updateByPrimaryKey(entity);
	}

	/**
	 * 通过主键更新，只是更新新的model中不为空的字段，空值对应字段不作处理
	 */
	@Override
	public int update(T entity) {
		return baseMapper.updateByPrimaryKeySelective(entity);
	}

	@Override
	public T get(String id) {
		return baseMapper.selectByPrimaryKey(id);
	}

	@Override
	public T selectOne(T entity) {
		return baseMapper.selectOne(entity);
	}

	@Override
	public List<T> getAll() {
		return baseMapper.selectAll();
	}

	@Override
	public List<T> select(T entity) {
		return baseMapper.select(entity);
	}
	
	@Override
	public  List<T> selectByExample(Object example){
        return baseMapper.selectByExample(example);
    }

	@Override
	public int deleteByExample(List<String> ids, T entity) {
		Example example = new Example(entity.getClass());
		Criteria criteria = example.createCriteria();
		criteria.andIn("id", new HashSet<>(ids));
		criteria.andEqualTo("isAvailable", Boolean.TRUE);
		return baseMapper.updateByExampleSelective(entity, example);
	}

}
